package com.qf.controller;

import com.qf.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 千峰教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
//@Controller
//@ResponseBody
@RestController
public class SysUserController {

    @RequestMapping("/doLogin")
    public Result doLogin(
            String username ,
            String password ,
            @RequestParam(name = "rememberMe", required = false, defaultValue = "false") boolean rememberMe){
        //获取subject
        Subject subject = SecurityUtils.getSubject();
        //创建token对象
        UsernamePasswordToken token = new UsernamePasswordToken(username, password,rememberMe);
        try {
            //执行登录操作
            subject.login(token);
            System.out.println(subject.isAuthenticated() ? "已认证": "认证失败");

            System.out.println(subject.hasRole("管理员")? "拥有管理员角色": "没有管理员角色");
            System.out.println(subject.hasRole("开发工程师")? "拥有开发工程师角色": "没有开发工程师角色");

            System.out.println(subject.isPermitted("sys:user:add")?"拥有用户添加权限":"没有用户添加权限");
            System.out.println(subject.isPermitted("sys:kaoqing:add")?"拥有考勤添加权限":"没有考勤添加权限");
        } catch (UnknownAccountException e){
            e.printStackTrace();
            return Result.error("未知的用户信息");
        } catch (IncorrectCredentialsException e){
            e.printStackTrace();
            return Result.error("密码错误");
        }catch (LockedAccountException e){
            e.printStackTrace();
            return Result.error("账户已锁定");
        } catch (AuthenticationException e){
            e.printStackTrace();
            return Result.error("认证失败");
        }

        return Result.ok();

    }

    @RequestMapping("/logout")
    public Object logout(){
        Subject subject = SecurityUtils.getSubject();
        //执行退出功能， 并清除session
        subject.logout();
        return  Result.ok("退出成功");
    }
}
